#include "usart.h"
#include "reg52.h"

unsigned char values[4];
unsigned char count;
unsigned char usart_close;
void Usart_write_Data(unsigned char dat)
{
	SBUF = dat;                     //Send current data
	while (!TI);                    //Wait for the previous data is sent
	TI = 0;                         //Clear TI flag
}

void Usart_write(unsigned char *str,int length)
{
	int i;
	EA = 0;
	for(i=0;i<length;i++)
	{
		Usart_write_Data(*str++);
	}
	EA = 1;
}

int Usart_read(unsigned char *rec,int length){
	char i;
	if(count>=length){
		count=0;
		for(i=0;i<length;i++){
			rec[i] = values[i];
		}
		return 1;
	}	
	return 0;
}

void Usart_ioctl(unsigned char *value,unsigned char cmd){
	if(cmd == USART_CLOSE){
		usart_close = *value;
	}
	if(cmd == USART_COUNT){
		count = *value;
	}
}

void Usart_open()   
{
    SCON = 0x50;                    //8 bit data ,no parity bit               
    TMOD = 0x20;                    //T1 as 8-bit auto reload
    TH1 = TL1 = -(FOSC/12/32/BAUD); //Set Uart baudrate
    TR1 = 1;                        //T1 start running
		ES=1;
		EA = 1;
}

void Usart_inter()interrupt 4
{
	if (RI)
	{
		RI = 0;             //Clear receive interrupt flag
		values[count] = SBUF;
		count++;
	}
}